package com.css.upms.biz.security.authentication;

import com.css.common.core.constent.CommonConstant;
import com.css.common.security.constant.SecurityConstants;
import com.css.common.security.support.CssUser;
import com.css.upms.api.entity.SysUser;
import com.css.upms.api.vo.UserInfo;
import com.css.upms.biz.service.SysUserService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * CssUserDetailsService
 *
 * @author hanyx
 * @date 2019/05/04
 */
@Slf4j
@AllArgsConstructor
@Service
public class CssUserDetailsService implements UserDetailsService {

    private final SysUserService userService;
    private final CacheManager cacheManager;

    /**
     * 用户密码登录
     *
     * @param username 用户名
     * @return
     */
    @Override
    @SneakyThrows
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = userService.getUserInfo(username);
        UserDetails userDetails = buildUserDetails(userInfo);
        return userDetails;
    }

    private CssUser buildUserDetails(UserInfo userInfo) {
        if (userInfo == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        Set<String> dbAuthsSet = new HashSet<>();
        if (ArrayUtils.isNotEmpty(userInfo.getRoles())) {
            // 获取角色
            Arrays.stream(userInfo.getRoles()).forEach(role -> dbAuthsSet.add(SecurityConstants.ROLE + role));
            // 获取资源
            dbAuthsSet.addAll(Arrays.asList(userInfo.getPermissions()));
        }

        Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
        SysUser user = userInfo.getSysUser();
        boolean isNormal = StringUtils.equals(user.getStatus(), CommonConstant.STATUS_NORMAL);
        boolean isDeleted = StringUtils.equals(user.getDelFlag(), CommonConstant.STATUS_NORMAL);
        // 构造security用户
        return new CssUser(user.getUserId(), user.getDeptId(), user.getUsername(), user.getPassword(),
                isDeleted, true, true, isNormal, authorities);
    }

}
